package com.example.mysql.jpa.optimistic_lock;

import com.example.common.util.ObjectUtil;
import com.example.mysql.jpa.domain.TestBean;
import com.example.mysql.jpa.repository.TestRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 演示说明在测试文件OptimisticLockTest
 */
@Component
public class OptimisticLockMethod
{
    private TestRepository testRepository;

    @Autowired
    public OptimisticLockMethod(TestRepository testRepository)
    {
        this.testRepository = testRepository;
    }

    @Transactional
    public void deleteDelayedCommit(Integer id, long second, String actionName)
    {
        testRepository.deleteById(id);
        if (second > 0)
        {
            System.out.println(String.format("%s已经删除[id: %s]，但是事务并没有提交", actionName, id));
            try
            {
                Thread.sleep(second * 1000);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        System.out.println(String.format("%s提交删除事务[id: %s]", actionName, id));
    }


    @Transactional
    public TestBean updateDelayedCommit(Integer id, Map<String, Object> values, long second, String actionName)
    {
        TestBean t = testRepository.getOne(id);
        TestBean testBean = new TestBean();
        BeanUtils.copyProperties(t, testBean);
        ObjectUtil.setValueByReflect(testBean, values);
        if (second > 0)
        {
            System.out.println(String.format("%s已经更新[id: %s]，但是事务并没有提交", actionName, id));
            try
            {
                Thread.sleep(second * 1000);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        TestBean rspTestBean = testRepository.save(testBean);
        System.out.println(String.format("%s提交更新事务[id: %s]", actionName, id));
        return rspTestBean;
    }
}
